// pages/materialApply/materialApply.js
import Dialog from '@vant/weapp/dialog/dialog';
import { createStoreBindings } from 'mobx-miniprogram-bindings'
import{materialApplyAdd}from"@/api/material"
import{getBorrowerDept}from"@/api/assetsBorrow"
import {selectedMaterial}from "@/store/numstore"
Page({
  data: {
    departments: [],
    selectedDepartmentIndex: null,
    materialApply:{
      user:"",
      expectedReturn:"",
      assignDate:"",
      deptId:"",
      locationId:"",
      type:1,
      userId:"",
      warehouseId:"",
      usagePurpose:"",
      assets:[]
    }
  },


  onLoad: function() {
    // 页面加载时初始化数据
    this.storeBindings =createStoreBindings(this,{
      store:selectedMaterial,
      fields:["selectedList","result"],
      actions:["update"]
    })
    this.setData({
      "materialApply.user":wx.getStorageSync("username"),
       "materialApply.userId":wx.getStorageSync('id')
    })
    this.getDeptByid(wx.getStorageSync('id'))

  },
  //获取部门
  async getDeptByid(id){
    const result=await getBorrowerDept(id)
    console.log(result);
    this.setData({
      departments:result.data.departments
    })
  },
  // 部门选择变化
  bindDepartmentChange: function(e) {
    console.log(e.detail.value);
    this.setData({
      selectedDepartmentIndex: e.detail.value,
      "materialApply.deptId":this.data.departments[e.detail.value].id
    });
  },
  
  // 日期选择变化
  bindDateChange: function(e) {
    this.setData({
      "materialApply.assignDate": e.detail.value,
      "materialApply.expectedReturn":e.detail.value
    });
  },
  // 扫码添加
  scanCode: function() {
    wx.scanCode({
      success: (res) => {
        console.log('扫码结果:', res.result);
        // 实际项目中应处理扫码结果
      }
    });
  },
  // 选择耗材
  selectMaterials: function() {
  
    wx.navigateTo({
      url: '/pages/materialSelect/materialSelect',
      events: {
        selectedMaterials: (data) => {
          
        const result= this.update(data.materials)
        console.log('选中的耗材:', data.materials,result);
          // 实际项目中应处理选中的耗材数据
          this.setData({
            "materialApply.assets": result,
            "materialApply.warehouseId":data.warehouseId
          });
        }
      }
    });
  },
    // 删除物料
    deleteMaterial: function(e) {
      const index = e.currentTarget.dataset.index;
      const selectedMaterials = [...this.data.selectedMaterials];
      selectedMaterials.splice(index, 1);
      this.setData({
        selectedMaterials
      });
    },
    onTextChange(e) {
      this.data.materialApply.usagePurpose = e.detail.value
    },
  // 提交表单
  async submitForm() {
    const { selectedDepartmentIndex} = this.data;
    // 表单验证
    if (selectedDepartmentIndex === null || selectedDepartmentIndex === undefined) {
      wx.showToast({ title: '请选择领用部门', icon: 'none' });
      return;
    }
    
    if (!this.data.materialApply.assignDate) {
      wx.showToast({ title: '请选择领用日期', icon: 'none' });
      return;
    }
    console.log(this.data.materialApply);
    this.data.materialApply.locationId=this.data.materialApply.warehouseId
    const result=await materialApplyAdd(this.data.materialApply);
    console.log(result);
    if(result.code==200){
      Dialog.alert({
        title: '系统提示',
        message: '领用成功',
      }).then(() => {
        wx.switchTab({
          url: '../index/index',
        })
      });
    }else{
    wx.showToast({ title: '领用失败', icon: 'error' });
    }   
  }
})